<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\Relation;
use app\common\model\UserNotify;
use think\exception\ValidateException;
use think\facade\View;
use app\common\model\User as UserModel;
use think\response\Json;
use app\common\tool\Result;
use app\common\model\Footprint;
use app\common\model\Product;
use app\common\model\Collect;
use app\common\model\Usercoupon;
use app\common\model\Order;
use app\common\model\Account;
use app\common\facade\WeChatMini;


class User extends Base
{
    //获取用户信息
    public function getUserInfo(){
        $status=[4,5];
        $this->user->zuji=Footprint::where(['uid'=>$this->user->id])->count();
        $this->user->shoucang=Collect::where(['uid'=>$this->user->id,'is_del'=>0])->count();
        $this->user->youhui=Usercoupon::where([['end_time','>=',time()],['status','=',0],['uid','=',$this->user->id],['is_del','=',0]])->count();
        $this->user->assets;
        $this->user->level;
        $bonus1=Order::whereIn('status',$status)->where(['commission_uid1'=>$this->user->id,'is_del'=>0])->sum('commission1');
        $bonus2=Order::whereIn('status',$status)->where(['commission_uid2'=>$this->user->id,'is_del'=>0])->sum('commission2');
        $ordercount=Order::whereIn('status',$status)->where(['commission_uid1|commission_uid2'=>$this->user->id,'is_del'=>0])->count();
        $this->user->bonus=Account::where(['uid'=>$this->user->id,'type'=>'bonus'])->sum('amount');
        $this->user->ordercount=$ordercount;
        $this->user->mobiles=substr_replace($this->user->mobile, '****',3, 4);
        $this->user->order1=Order::where(['uid'=>$this->user->id,'is_del'=>0,'status'=>1])->count();
        $this->user->order2=Order::where(['uid'=>$this->user->id,'is_del'=>0,'status'=>2])->count();
        $this->user->order3=Order::where(['uid'=>$this->user->id,'is_del'=>0,'status'=>3])->count();
        $this->user->order5=Order::where(['uid'=>$this->user->id,'is_del'=>0,'status'=>5,'is_read'=>0])->count();
        $this->user->order7=Order::where(['uid'=>$this->user->id,'is_del'=>0,'status'=>7])->count();
        return Result::success('获取数据成功！',$this->user);
    }
    //获取分享
    public function getUserQrcode(){
        $param = $this->request->get();
        $url='/qrcode/user';
        $result = WeChatMini::getMiniScene($this->user->id,'share_'.$this->user->id,'240','pages/index/index', $url);
        return Result::success('获取成功！',$result);
    }
    //修改头像
    public function savePhoto(){
        $param = $this->request->post('', '', $this->filter);
        return Result::fastReturn(UserModel::savePhoto($param, $this->user));
    }
    
    //修改昵称
    public function saveNickname(){
        $param = $this->request->post('', '', $this->filter);
        return Result::fastReturn(UserModel::saveNickname($param, $this->user));
    }
    //获取账户信息列表
    public function getMyAccount(){
        $param=$this->request->param();
        $page = $param['page'];
        $num=20;
        if($page==1){
            $start=0;
        }else{
            $start=$page*$num-$num;
        }
        $list=Account::where(['uid'=>$this->user->id,'type'=>'bonus'])->order('create_time desc')->limit($start,$num)->select();
       
        return Result::success('获取数据成功！',$list);
    }
    //获取用户足迹
    public function getFootPrint(){
        $param=$this->request->param();
        $page = $param['page'];
        $num=20;
        if($page==1){
            $start=0;
        }else{
            $start=$page*$num-$num;
        }
        if(isset($param['user_id']) && $param['user_id']!=0){
            $uid=$param['user_id'];
        }else{
            $uid=$this->user->id;
        }
        $ufind=UserModel::where('id',$uid)->field("id,nickname,photo,mobile")->find();
        $ufind['count']=Footprint::where(['uid'=>$uid])->count();
        // $ufind['mobiles']=substr_replace($ufind->mobile, '****',3, 4);
        $ufind['mobiles']=$ufind->mobile;
        $lists=Footprint::where(['uid'=>$uid])->field("from_unixtime(create_time,'%Y-%m-%d') as time,group_concat(product_id)")->order('time desc')->group('time')->limit($start,$num)->select();
        foreach($lists as $k=>$v){
            $ids=explode(',',$v['group_concat(product_id)']);
            $v['product']=Product::whereIn('id',$ids)->field('id,title,price,vip_price,icon,sales')->select();
            if(strtotime($v['time'])==strtotime(date("Y-m-d"),time())){
                $v['times']='今天';
            }else{
                $v['times']=date('m月d日',strtotime($v['time']));
            }
            $lists[$k]=$v;
        }
        $list['user']=$ufind;
        $list['list']=$lists;
        //print('<pre>');print_r($list);die;
        return Result::success('获取数据成功！',$list);
    }
    //获取客户足迹列表
    public function getClientFootPrint(){
        $param=$this->request->param();
        $page = $param['page'];
        $num=20;
        if($page==1){
            $start=0;
        }else{
            $start=$page*$num-$num;
        }
        $list=Order::where('commission_uid1|commission_uid2',$this->user->id)->with('user')->field("id,uid")->group('uid')->limit($start,$num)->select();
        foreach($list as $k=>$v){
            $v['count']=Footprint::where(['uid'=>$v['uid']])->count();
            // $v->user->mobiles=substr_replace($v->user->mobile, '****',3, 4);
            $v->user->mobiles=$v->user->mobile;
            $list[$k]=$v;
        }
        return Result::success('获取数据成功！',$list);
    }
    public function index(): Json
    {
        $result = [
            'nickname' => $this->user->nickname,
            'code' => $this->user->code,
            'photo' => $this->user->photo,
            'is_active' => $this->user->is_active == 1 ? '普通会员' : '正式会员',
            'level' => $this->user->level ? $this->user->level->title : '',
            'mobile' => $this->user->mobile ?: '',
            'parent_code' => $this->user->parent_code ?: '',
        ];
        return json(['code' => 1, 'msg' => 'success', 'result' => $result]);
    }

    public function setting()
    {
        return View::fetch();
    }

    public function my_team()
    {

        $page = $this->request->param('page', 1);
        $map = ['uid' => $this->user->id, 'algebra' => 1];
        $list = Relation::getPageList($map, 'id,uid,new_uid,create_time', $page, 20, false, ['fresh']);
        foreach ($list['result'] as $k => $v) {
            $v->code = $v->fresh->code;
            $v->mobile = $v->fresh->mobile;
            $v->team_total = $v->fresh->team_total;
            unset($v->id);
            unset($v->uid);
            unset($v->new_uid);
            unset($v->fresh);
        }
        $team = [];
        if ($page == 1) {
            $dpn = Relation::where(['uid' => $this->user->id, 'algebra' => 1])->column('new_uid');
            $team = Relation::where('uid', $this->user->id)->count();
            $team = [
                'dpn' => count($dpn),
                'dpn_total' => UserModel::whereIn('id', $dpn)->sum('my_total'),
                'team' => $team,
                'team_total' => $this->user->team_total
            ];
        }
        return json(['code' => 1, 'msg' => 'success', 'result' => [
            'team' => $team, 'list' => $list['result'], 'pages' => $list['pages']
        ]]);
    }

    public function method_index()
    {
        $mode = [
            ['name' => '支付宝', 'type' => 'alipay'],
            ['name' => '微信', 'type' => 'wechat'],
            ['name' => '银行卡', 'type' => 'bank']
        ];
        return json(['code' => 1, 'msg' => 'success', 'result' => $mode]);
    }
    //获取类型
    public function method_info()
    {
        $type=$this->request->param('type');
        switch ($type) {
            case "alipay":
            case "wechat":
                $name = $type . '_name';
                $image = $type . '_image';
                $result['name'] = $this->user->$name;
                $result['image'] = handleImg($this->user->$image);
                break;
            case "bank":
                $result['bank_name'] = $this->user->bank_name;
                $result['bank_open'] = $this->user->bank_open;
                $result['bank_account_name'] = $this->user->bank_account_name;
                //$result['bank_number'] = $this->user->bank_number;
                //$result['bank_list'] = explode(PHP_EOL, $this->system['bank_list']);
                break;
            default:
                return json(['code' => -1, 'msg' => '加载失败']);

        }
        return Result::success('获取数据成功！',$result);
    }
    //收款方式
    public function method_save()
    {
        try {
            $param = $this->request->post();
            $type=$param['type'];
            $v = $type == 'bank' ? 'MethodBank' : 'MethodImg';
            try {
                $this->validate($param, $v);
            } catch (ValidateException $e) {
                return Result::fail($e->getError());
            }
            switch ($type) {
                case "bank":
                    break;
                default:
                    $param[$type . '_name'] = $param['name'];
                    $param[$type . '_image'] = $param['image'];
                    unset($param['name']);
                    unset($param['image']);
            }

            UserModel::update($param, ['id' => $this->user->id]);

            return Result::success('已保存');

        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    public function edit()
    {
        $param = $this->request->post('', '', $this->filter);
        return json(UserModel::_miniAppletEdit($param, $this->user));
    }

    public function notify($type)
    {
        $param = $this->request->param();

        if ($type == 1) {
            $count = UserNotify::where(['uid' => $this->user->id, 'is_read' => 0])->count();
            return json(['code' => 1, 'msg' => 'success', 'result' => $count]);
        } else {
            $map = ['uid' => $this->user->id, 'is_del' => 0];

            return json(UserNotify::getPageList($map, 'id,type,content,is_read,create_time', $param['page'], 20, false));
        }


    }


}

